import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:intl/intl.dart';

String ensureUpdateJson(String url) {
  if (url.endsWith('update.json')) {
    return url;
  }
  if (url.endsWith('/')) {
    return '${url}update.json';
  }
  return '$url/update.json';
}

String formatLogTime() {
  return DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
}

bool isBackupFile(String filename) {
  return filename.lastIndexOf(".") != filename.indexOf(".") ||
      RegExp(r'\d+(?:bk|bak)|(?:bk|bak)\d+').hasMatch(filename);
}

Future<String> computeFileMd5(String filePath) async {
  final file = File(filePath);
  if (!await file.exists()) return '';
  final bytes = await file.readAsBytes();
  final hash = md5.convert(bytes);
  return hash.toString();
}

Future<void> ensureDirectoryExists(String dirPath) async {
  final dir = Directory(dirPath);
  if (!await dir.exists()) {
    await dir.create(recursive: true);
  }
}

Future<void> cleanDirectory(String dirPath) async {
  try{
    final dir = Directory(dirPath);
    if (await dir.exists()) {
      await dir.delete(recursive: true);
    }
    await dir.create(recursive: true);
  }catch(ex){
    print(ex);
  }
}
